<template>
  <div id="InterfaceDictDiv">
    <Breadcrumb content="预制场景设置" />
    <div class="bodyContent">
      <Splitpanes>
        <!-- 左侧表格  -->
        <Pane size="40">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findInterfaceDictList" @keyup="keyupEnter" @search-click="findInterfaceDictList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="tloading" @click="findInterfaceDictList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addInterfaceDictDialog()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteBatchInterfaceDict"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table ref="InterfaceDictTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" height="auto" :data="InterfaceDictList" :loading="tloading" @current-change="InterfaceDictRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30"></vxe-column>
              <vxe-column field="ownSystemName" title="所属系统" width="100"></vxe-column>
              <vxe-column field="typeName" title="接口类别" width="100"></vxe-column>
              <vxe-column field="interfaceGroupName" title="分组类型" width="120" align="left"></vxe-column>
              <vxe-column field="orderCode" title="编码" width="120" align="left"></vxe-column>
              <vxe-column field="code" title="方法代码" width="120" align="left"></vxe-column>
              <vxe-column field="name" title="方法名称" width="200"></vxe-column>
              <vxe-column field="url" title="路径" min-width="120"></vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <!-- 右侧表单 -->
        <Pane size="60">
          <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
            <el-tab-pane label="基础信息" name="first">
              <el-scrollbar style="height: 100%">
                <el-form ref="InterfaceDictFormRef" :model="InterfaceDictForm" :rules="InterfaceDictFormRule" label-width="100px" inline-message>
                  <el-row>
                    <el-col :span="20">
                      <el-form-item prop="code" label="方法代码">
                        <el-input type="text" v-model="InterfaceDictForm.code" placeholder="请输入方法代码" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="20">
                      <el-form-item prop="name" label="方法名称">
                        <el-input type="text" v-model="InterfaceDictForm.name" placeholder="请输入方法名称	" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item prop="orderCode" label="编码">
                        <el-input type="text" v-model="InterfaceDictForm.orderCode" placeholder="请输入编码	" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="20">
                      <el-form-item prop="type" label="接口类别">
                        <el-select ref="refType" v-model="InterfaceDictForm.type" filterable placeholder="请选择接口类别" multiple>
                          <el-option v-for="intf in interfaceTypeList" :key="intf.code" :label="intf.name" :value="intf.code"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="20">
                      <el-form-item prop="ownSystem" label="所属模块">
                        <el-select ref="refOwnSystem" v-model="InterfaceDictForm.ownSystem" filterable placeholder="请选择所属模块" multiple>
                          <el-option v-for="module in moduleList" :key="module.id" :label="module.name" :value="module.id"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="20">
                      <el-form-item prop="interfaceGroup" label="所属系统">
                        <el-select ref="refInterfaceGroup" v-model="InterfaceDictForm.interfaceGroup" filterable placeholder="请选择所属系统" multiple>
                          <el-option v-for="item in interfaceGroups" :key="item.commonId" :label="item.name" :value="item.commonId" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="20">
                      <el-form-item prop="sceneType" label="场景类别">
                        <el-input type="text" v-model="InterfaceDictForm.sceneType" placeholder="请输入场景类别	" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="20">
                      <el-form-item prop="url" label="方法路径">
                        <el-input type="text" v-model="InterfaceDictForm.url" placeholder="请输入方法路径	" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="20">
                      <el-form-item prop="dataType" label="数据方式">
                        <el-radio-group v-model="InterfaceDictForm.dataType">
                          <el-radio :label="1">拉取</el-radio>
                          <el-radio :label="2">推送</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="20">
                      <el-form-item prop="sqlType" label="sql类型">
                        <el-select v-model="InterfaceDictForm.sqlType" placeholder="请选择">
                          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>

                    <el-col :span="20">
                      <el-form-item prop="orderNum" label="使用说明">
                        <el-input type="textarea" :autosize="{ minRows: 20, maxRows: 25 }" v-model="InterfaceDictForm.remark" />
                      </el-form-item>
                    </el-col>

                    <el-col :span="24">
                      <el-form-item class="form-footer">
                        <template #default>
                          <el-button type="primary" @click="saveInterfaceDict('InterfaceDictFormRef')">保存</el-button>
                        </template>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane label="入参" name="second" :disabled="isEmpty(InterfaceDictForm.id)">
              <InterfaceDictAttribute ref="InterfaceDictInParamRef" />
            </el-tab-pane>
            <el-tab-pane label="出参" name="thrid" v-if="InterfaceDictForm.dataType == 1" :disabled="isEmpty(InterfaceDictForm.id)">
              <InterfaceDictAttribute ref="InterfaceDictOutParamRef" />
            </el-tab-pane>
            <el-tab-pane label="场景参数设置" name="four" :disabled="isEmpty(InterfaceDictForm.id)">
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class="smallToolTitle">参数类型</div>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" @click="findParamFieldList"></vxe-button>
                  <div class="saveBtn">
                    <vxe-button type="text" content="保存" class="button-blue margin-left-xs" @click="saveParamFieldList"></vxe-button>
                  </div>
                </template>
              </vxe-toolbar>
              <Splitpanes style="height: 100%">
                <Pane size="10">
                  <div class="padding-lr-xs">
                    <vxe-button type="text" content="输入框" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('input')"></vxe-button>
                    <vxe-button type="text" content="数值框" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('integer')"></vxe-button>
                    <vxe-button type="text" content="日期选择" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('date')"></vxe-button>
                    <vxe-button type="text" content="复选框" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('checkbox')"></vxe-button>
                    <vxe-button type="text" content="复选框组" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('checkboxgroup')"></vxe-button>
                    <!-- <vxe-button
                      type="text"
                      content="单选按钮组"
                      class="button-blue margin-tb-xs"
                      style="width: 100%"
                      @click="addFormItem('radiogroup')"
                    ></vxe-button>
                    <vxe-button
                      type="text"
                      content="开关按钮"
                      class="button-blue margin-tb-xs"
                      style="width: 100%"
                      @click="addFormItem('switch')"
                    ></vxe-button>-->
                    <vxe-button type="text" content="下拉选择" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('select')"></vxe-button>
                    <!-- <vxe-button
                      type="text"
                      content="文本域"
                      class="button-blue margin-tb-xs"
                      style="width: 100%"
                      @click="addFormItem('textarea')"
                    ></vxe-button>
                    <vxe-button
                      type="text"
                      content="颜色框"
                      class="button-blue margin-tb-xs"
                      style="width: 100%"
                      @click="addFormItem('color')"
                    ></vxe-button>-->
                    <!-- <vxe-button
                      type="text"
                      content="下拉业务表"
                      class="button-blue margin-tb-xs"
                      style="width: 100%"
                      @click="addFormItem('sltBusTable')"
                    ></vxe-button>
                    <vxe-button
                      type="text"
                      content="多选业务表"
                      class="button-blue margin-tb-xs"
                      style="width: 100%"
                      @click="addFormItem('checkBusTable')"
                    ></vxe-button>-->
                  </div>
                </Pane>
                <Pane size="55">
                  <vxe-toolbar perfect>
                    <template #buttons>
                      <div class="toolbartitle">详情</div>
                    </template>
                  </vxe-toolbar>

                  <div class="padding-lr-xs formBox">
                    <el-scrollbar height="100%">
                      <vxe-form :data="formData">
                        <vxe-form-item class="padding-lr-xs" :class-name="formItm.isCurrent ? 'dashed lines-orange bg-blue light' : ''" :align="formItm.align" :title="formItm.title" :field="formItm.field" :title-width="formItm.titleWidth" :title-colon="formItm.titleColon === 1" :title-asterisk="formItm.titleAsterisk === 1" :title-overflow="formItm.titleOverflow === 1" :show-title="formItm.showTitle === 1" :title-align="formItm.titleAlign" :vertical="formItm.vertical === 1" :content-class-name="formItm.contentClassName" :visible="formItm.visible === 1" :span="formItm.span" v-for="(formItm, formIdx) in paramFieldList" :key="formIdx">
                          <template #title>
                            <div @click="formItemCLick(formItm, formIdx)">
                              <span class="padding-left-xs">{{ `${formItm.code} ${formItm.title}` }}</span>
                            </div>
                          </template>
                          <template #default="params">
                            <div class="flex justify-start" @click="formItemCLick(formItm, formIdx)">
                              <vxe-input v-if="formItm.compType === 'input'" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
                              <vxe-input v-if="formItm.compType === 'date' || formItm.compType === 'datetime'" :type="formItm.compType === 'date' ? 'date' : 'datetime'" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
                              <vxe-checkbox-group v-if="formItm.compType === 'checkboxgroup'" @click="changeEvent(params)">
                                <vxe-checkbox :label="itm.label" :content="itm.content" v-for="(itm, idx) in formItm.fieldOptions" :key="idx"></vxe-checkbox>
                              </vxe-checkbox-group>
                              <vxe-radio-group v-if="formItm.compType === 'radiogroup'">
                                <vxe-radio :label="itm.label" :content="itm.content" v-for="(itm, idx) in formItm.fieldOptions" :key="idx"></vxe-radio>
                              </vxe-radio-group>
                              <vxe-checkbox v-if="formItm.compType === 'checkbox'"></vxe-checkbox>
                              <vxe-input v-if="formItm.compType === 'integer'" type="integer" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
                              <vxe-switch v-if="formItm.compType === 'switch'" open-value="1" close-value="0"></vxe-switch>
                              <vxe-select v-if="formItm.compType === 'select'" placeholder="请选择">
                                <vxe-option v-for="(itm, idx) in formItm.fieldOptions" :key="idx" :value="itm.label" :label="itm.content"></vxe-option>
                              </vxe-select>
                              <vxe-textarea v-if="formItm.compType === 'textarea'" placeholder="请输入"></vxe-textarea>
                              <vxe-select v-if="formItm.compType === 'sltBusTable'" placeholder="可清除" transfer clearable @focus="getTableDataList(formItm)">
                                <vxe-option v-for="(tableData, index) in tableDataList" :key="index" :value="tableData[formItm.correValue]" :label="tableData[formItm.correLabel]"></vxe-option>
                              </vxe-select>
                              <vxe-select v-if="formItm.compType === 'checkBusTable'" placeholder="可清除" transfer multiple clearable @focus="getTableDataList(formItm)">
                                <vxe-option v-for="(tableData, index) in tableDataList" :key="index" :value="tableData[formItm.correValue]" :label="tableData[formItm.correLabel]"></vxe-option>
                              </vxe-select>

                              <el-color-picker v-if="formItm.compType === 'color'" />

                              <vxe-button type="text" class="button-red right-Btn" icon="vxe-icon-delete" @click="deleteParamField(formItm)"></vxe-button>
                            </div>
                          </template>
                        </vxe-form-item>
                      </vxe-form>
                    </el-scrollbar>
                  </div>
                </Pane>
                <Pane size="35">
                  <el-tabs type="border-card">
                    <el-tab-pane label="基本属性">
                      <div class="padding-lr-xs">
                        <vxe-form title-width="90" v-if="showGroupDialog" ref="formRef" :data="fieldFormData" title-align="right">
                          <vxe-form-item title="编号" field="code" span="24">
                            <template #default="params">
                              <vxe-input v-model="params.data.code" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
                            </template>
                          </vxe-form-item>
                          <vxe-form-item title="属性名" field="field" span="24">
                            <template #default="params">
                              <vxe-input v-model="params.data.field" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
                            </template>
                          </vxe-form-item>
                          <vxe-form-item title="标题" field="title" span="24">
                            <template #default="params">
                              <vxe-input v-model="params.data.title" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
                            </template>
                          </vxe-form-item>
                          <vxe-form-item title="占比" field="span" span="24">
                            <template #default="params">
                              <vxe-input type="integer" v-model="params.data.span" placeholder="请输入0-24" clearable @change="changeEvent(params)" min="1" max="24"></vxe-input>
                            </template>
                          </vxe-form-item>
                          <vxe-form-item title="标题宽度" field="titleWidth" span="24">
                            <template #default="params">
                              <vxe-input type="integer" v-model="params.data.titleWidth" placeholder="请输入0-200" clearable @change="changeEvent(params)" min="1" max="200">
                                <template #suffix>
                                  <span>px</span>
                                </template>
                              </vxe-input>
                            </template>
                          </vxe-form-item>
                          <vxe-form-item title="备注" field="remark" span="24">
                            <template #default="params">
                              <vxe-textarea v-model="params.data.remark" placeholder="请输入" clearable></vxe-textarea>
                            </template>
                          </vxe-form-item>
                          <vxe-form-item title="顺序号" field="seq" span="24">
                            <template #default="params">
                              <vxe-input type="number" v-model="params.data.seq" placeholder="请输入" clearable @blur="sortAgain"></vxe-input>
                            </template>
                          </vxe-form-item>
                          <vxe-form-item v-if="sltGroup && paramFieldList[sltGroup.editFormItemIndex] && paramFieldList[sltGroup.editFormItemIndex].compType && (paramFieldList[sltGroup.editFormItemIndex].compType === 'select' || paramFieldList[sltGroup.editFormItemIndex].compType === 'radiogroup' || paramFieldList[sltGroup.editFormItemIndex].compType === 'checkboxgroup')" title="数据来源" field="fieldSource" span="24" :item-render="{}" title-overflow>
                            <template #default="params">
                              <vxe-select v-model="params.data.fieldSource" placeholder="请选择数据来源" clearable @change="changeEvent(params)">
                                <vxe-option value="1" label="字典"></vxe-option>
                                <vxe-option value="2" label="业务表"></vxe-option>
                                <vxe-option value="3" label="固定数组"></vxe-option>
                              </vxe-select>
                            </template>
                          </vxe-form-item>

                          <vxe-form-item v-if="sltGroup && paramFieldList[sltGroup.editFormItemIndex] && paramFieldList[sltGroup.editFormItemIndex].compType && (paramFieldList[sltGroup.editFormItemIndex].compType === 'sltBusTable' || paramFieldList[sltGroup.editFormItemIndex].compType === 'checkBusTable')" title="选择表" field="correTable" span="24" :item-render="{}" title-overflow>
                            <template #default="params">
                              <SelectDataList ref="employeeSelectRef" :url="'/api/sys/basDictTable/findAllTableList'" :displayField="[
                                { title: '编号', props: 'TABLE_NAME' }, //列标题
                                { title: '名称', props: 'COMMENTS' }
                              ]" :searchParam="{
                                //seachValue: form.hisEmployeeCode
                              }" :inputKeyName="'seachValue'" :isPage="false" :title="'点击选择表'" @selectDataRow="SelectRowClick" @clearValue="clearValueHandler" @sliceValue="sliceHandler" v-model="params.data.correTable" />
                            </template>
                          </vxe-form-item>

                          <vxe-form-item v-if="sltGroup && paramFieldList[sltGroup.editFormItemIndex] && paramFieldList[sltGroup.editFormItemIndex].compType && (paramFieldList[sltGroup.editFormItemIndex].compType === 'sltBusTable' || paramFieldList[sltGroup.editFormItemIndex].compType === 'checkBusTable')" title="选择Label" field="correLabel" span="24" :item-render="{}" title-overflow>
                            <template #default="params">
                              <vxe-select v-model="params.data.correLabel" placeholder="请选择表字段" clearable>
                                <vxe-option v-for="correColumn in correColumnList" :key="correColumn.columnId" :label="correColumn.comments" :value="correColumn.columnName"></vxe-option>
                              </vxe-select>
                            </template>
                          </vxe-form-item>
                          <vxe-form-item v-if="paramFieldList[sltGroup.editFormItemIndex] && paramFieldList[sltGroup.editFormItemIndex].compType && (paramFieldList[sltGroup.editFormItemIndex].compType === 'sltBusTable' || paramFieldList[sltGroup.editFormItemIndex].compType === 'checkBusTable')" title="选择Value" field="correValue" span="24" :item-render="{}" title-overflow>
                            <template #default="params">
                              <vxe-select v-model="params.data.correValue" placeholder="请选择表字段" clearable>
                                <vxe-option v-for="correColumn in correColumnList" :key="correColumn.columnId" :label="correColumn.comments" :value="correColumn.columnName"></vxe-option>
                              </vxe-select>
                            </template>
                          </vxe-form-item>
                        </vxe-form>
                        <vxe-toolbar v-if="sltGroup && paramFieldList[sltGroup.editFormItemIndex] && paramFieldList[sltGroup.editFormItemIndex].compType && (paramFieldList[sltGroup.editFormItemIndex].compType === 'select' || paramFieldList[sltGroup.editFormItemIndex].compType === 'radiogroup' || paramFieldList[sltGroup.editFormItemIndex].compType === 'checkboxgroup')" perfect class-name="bg-gray">
                          <template #buttons>
                            <span class="text-bold">可取值</span>
                          </template>
                          <template #tools>
                            <vxe-button type="text" class="button-red deleteValueBtn" content="删除" @click="removeSelectRowEvent"></vxe-button>
                            <vxe-button type="text" class="button-blue" content="添加" @click="insertEvent"></vxe-button>
                          </template>
                        </vxe-toolbar>
                        <div v-if="sltGroup && paramFieldList[sltGroup.editFormItemIndex] && paramFieldList[sltGroup.editFormItemIndex].compType && (paramFieldList[sltGroup.editFormItemIndex].compType === 'select' || paramFieldList[sltGroup.editFormItemIndex].compType === 'radiogroup' || paramFieldList[sltGroup.editFormItemIndex].compType === 'checkboxgroup')">
                          <vxe-table border align="center" show-overflow keep-source height="auto" :row-config="{ isCurrent: true }" :data="paramFieldList[sltGroup.editFormItemIndex].fieldOptions" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: false }" ref="xTableOptions">
                            <vxe-column type="seq" title="#" width="30"></vxe-column>
                            <vxe-column field="label" title="选项值" :edit-render="{ autofocus: '.vxe-input--inner' }">
                              <template #edit="{ row }">
                                <vxe-input v-model="row.label" type="text"></vxe-input>
                              </template>
                            </vxe-column>
                            <vxe-column field="content" title="选项描述" :edit-render="{ autofocus: '.vxe-input--inner' }">
                              <template #edit="{ row }">
                                <vxe-input v-model="row.content" type="text"></vxe-input>
                              </template>
                            </vxe-column>
                          </vxe-table>
                        </div>
                      </div>
                    </el-tab-pane>
                    <!-- <el-tab-pane label="页签属性">
                      <div class="padding-lr-xs">
                        <el-form
                          :ref="'groupEditFormRef' + idx"
                          :model="editGroupForm"
                          :rules="groupFormRule"
                          label-width="100px"
                          class="form-input-m"
                          inline-message
                        >
                          <el-row>
                            <el-col :span="24">
                              <el-form-item prop="code" label="编号">
                                <el-input
                                  type="text"
                                  v-model="editGroupForm.code"
                                  placeholder="请输入分组编号"
                                  clearable
                                ></el-input>
                              </el-form-item>
                            </el-col>
                            <el-col :span="24">
                              <el-form-item prop="title" label="名称">
                                <el-input
                                  type="text"
                                  v-model="editGroupForm.title"
                                  placeholder="请输入分组名称"
                                  clearable
                                ></el-input>
                              </el-form-item>
                            </el-col>
                            <el-col :span="24">
                              <el-form-item prop="order" label="排序">
                                <el-input-number v-model="editGroupForm.seq" :min="1" :max="1000" />
                              </el-form-item>
                            </el-col>
                          </el-row>
                        </el-form>

                        <div class="dialog-footer flex right justify-end">
                          <vxe-button
                            type="text"
                            content="保存"
                            class="button-blue margin-left-xs"
                            @click="editGroup('groupEditFormRef' + idx)"
                          ></vxe-button>
                        </div>
                      </div>
                    </el-tab-pane>-->
                  </el-tabs>
                </Pane>
              </Splitpanes>
              <div v-if="!groupList || groupList.length <= 0">
                <noData :msg="'暂无配置项'"></noData>
              </div>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { isEmpty } from 'lodash';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
import SelectDataList from '@/components/SelectDataList.vue';
import InterfaceDictAttribute from './InterfaceDictAttribute.vue';
import { AppStore } from '@/stores/store';

let store = AppStore();
let searchForm = {
  searchValue: '',
  rptGroupId: ''
};
let tloading = ref(false); //加载状态
let activeName = ref('first');
let InterfaceDictList: any = reactive([]);
let sltInterfaceDict: any = ref({});
let InterfaceDictInParamRef: any = ref(null);
let InterfaceDictOutParamRef: any = ref(null);

let sysParamList: any = reactive([]);
let groupList: any = reactive([]);
let paramFieldList: any = reactive([]);
let sltSysParam: any = reactive({});
let correColumnList: any = reactive([]);
let tableDataList: any = reactive([]); //选择动态表集合
let showGroupDialog = ref(false);
let fieldFormData = ref({});
let moduleList = reactive([]);
let interfaceTypeList = reactive([]);

let disabledTag = ref(true);
let formData: any = {};
let sltGroup: any = {};
let searchGroupForm = { searchValue: '' };
const interfaceGroups = reactive([]); //接口分组类型

const options = reactive([
  { label: '查询', value: 1 },
  { label: '新增', value: 2 },
  { label: '修改', value: 3 },
  { label: '删除', value: 4 },
  { label: '存储过程', value: 5 }
])
// 通用行合并函数（将相同多列数据合并为一行）
/*const mergeRowMethod = ({ row, _rowIndex, column, visibleData }) => {
  const fields = ['interfaceGroupName']
  const cellValue = row[column.field]
  if (cellValue && fields.includes(column.field)) {
    const prevRow = visibleData[_rowIndex - 1]
    let nextRow = visibleData[_rowIndex + 1]
    if (prevRow && prevRow[column.field] === cellValue) {
      return { rowspan: 0, colspan: 0 }
    } else {
      let countRowspan = 1
      while (nextRow && nextRow[column.field] === cellValue) {
        nextRow = visibleData[++countRowspan + _rowIndex]
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 }
      }
    }
  }
}*/
let sysParamForm = reactive({
  id: null,
  code: '',
  name: '',
  seq: 0,
  orgId: '',
  remark: '',
  moduleId: '',
  classify: '',
  isEdit: true,
  isLocal: false,
  isComputer: false
});
let sysParamFormRule = {
  name: [
    {
      required: true,
      message: '请输入字段名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

let addGroupForm = reactive({
  id: null,
  pid: null,
  grade: 0,
  code: '',
  title: '',
  seq: 0,
  orgId: '',
  remark: ''
});
let editGroupForm = reactive({
  id: null,
  pid: null,
  grade: 0,
  code: '',
  title: '',
  seq: 0,
  orgId: '',
  remark: ''
});
let groupFormRule = {
  title: [
    {
      required: true,
      message: '请输入字段名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

let InterfaceDictForm = reactive({
  id: null,
  name: '',
  code: '',
  interfaceGroup: [],
  type: [],
  ownSystem: [],
  orderCode: '',
  explain: '',
  orgId: '',
  remark: '',
  dataType: 1,
  sqlType: 1,
  sceneType: '',
  settings: [],
  typeName: '',
  ownSystemName: '',
  interfaceGroupName: ''
});

let InterfaceDictFormRule = {
  name: [
    {
      required: true,
      message: '请输入方法名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 100,
      message: '长度为2到100个字符',
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: '请输入方法代码',
      trigger: 'blur'
    }
  ],
  orderCode: [
    {
      required: true,
      message: '请输入方法代码',
      trigger: 'blur'
    }
  ],
  url: [
    {
      required: true,
      message: '请输入方法路径',
      trigger: 'blur'
    }
  ]
};

onMounted(() => {
  findInterfaceDictList(); // 获取质控规则表格数据
  getModuleList();
  getDictItemsList();
  //findSysParamList();
  //findParamFieldList();
});

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['interfaceClassify', 'InterfaceSystem'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const severityType = dictTreeTypeItems.data.find((item) => item.code === 'interfaceClassify');
  const interfaceType = dictTreeTypeItems.data.find((item) => item.code === 'InterfaceSystem');
  interfaceTypeList.push(...severityType.detailDataList);
  interfaceGroups.push(...interfaceType.detailDataList);
  // console.log('interfaceGroups',interfaceGroups)
}

function tabHandleClick(tab) {
  if (tab.index == 1) {
    InterfaceDictInParamRef.value.initPage(InterfaceDictForm.id, 1);
  } else if (tab.index == 2) {
    InterfaceDictOutParamRef.value.initPage(InterfaceDictForm.id, 2);
  }
}
// 请求模块表格数据
function getModuleList() {
  let modulePageParam = {
    params: {
      pageIndex: 1,
      pageSize: 9999
    }
  };
  moduleList.length = 0; //放入数据前清空数组
  proxy.$http.get('/api/sys/getPageModules', modulePageParam).then((res: any) => {
    if (res.status.code === 1) {
      moduleList.push(...res.data.modulePageList.records);
    } else {
      VXETable.modal.message({ content: res.status.msg, status: 'error' });
      return;
    }
  });
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findInterfaceDictList();
  }
}
function findInterfaceDictList() {
  tloading.value = true;
  InterfaceDictList.length = 0; //放入数据前清空数据
  const url = '/api/sys/getInterfaceDictList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        keyWords: searchForm.searchValue
      }
    })
    .then((res: any) => {
      InterfaceDictList.push(...res.data);
      tloading.value = false;
      if (InterfaceDictList.length > 0) {
        InterfaceDictRowClick({ row: InterfaceDictList[0] }); //默认选中第一条数据
      } else {
        activeName.value = 'first';
        clearForm();
      }
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function InterfaceDictRowClick({ row }: any) {
  const el: any = proxy.$refs['InterfaceDictFormRef'];
  //移除校验结果
  el.clearValidate();

  if (isEmpty(row)) {
    clearForm();
  } else {
    (proxy.$refs.InterfaceDictTableRef as any).setCurrentRow(row);
    setInterfaceDictForm(row);
    if (activeName.value == 'second') {
      InterfaceDictInParamRef.value.initPage(InterfaceDictForm.id, 1);
    } else if (activeName.value == 'thrid') {
      InterfaceDictOutParamRef.value.initPage(InterfaceDictForm.id, 2);
    } else {
      findParamFieldList();
    }
  }
}

function addInterfaceDictDialog() {
  clearForm();
  (proxy.$refs.InterfaceDictTableRef as any).clearCurrentRow();
  activeName.value = 'first';
}
function saveInterfaceDict(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }

    const refType = proxy.$refs.refType as any;
    if (refType) {
      InterfaceDictForm.typeName = refType.$el.innerText;
    }
    const refOwnSystem = proxy.$refs.refOwnSystem as any;
    if (refOwnSystem) {
      InterfaceDictForm.ownSystemName = refOwnSystem.$el.innerText;
    }
    const refInterfaceGroup = proxy.$refs.refInterfaceGroup as any;
    if (refInterfaceGroup) {
      InterfaceDictForm.interfaceGroupName = refInterfaceGroup.$el.innerText;
    }
    let url = '';
    if (InterfaceDictForm.id == null) {
      url = '/api/sys/addInterfaceDict';
    } else {
      // 修改用户
      url = '/api/sys/editInterfaceDict';
    }
    const InterfaceDict = {
      id: InterfaceDictForm.id,
      name: InterfaceDictForm.name,
      code: InterfaceDictForm.code,
      type: InterfaceDictForm.type.join(','),
      interfaceGroup: InterfaceDictForm.interfaceGroup.join(','),
      ownSystem: InterfaceDictForm.ownSystem.join(','),

      typeName: InterfaceDictForm.typeName,
      interfaceGroupName: InterfaceDictForm.interfaceGroupName,
      ownSystemName: InterfaceDictForm.ownSystemName,

      workFlowId: InterfaceDictForm.workFlowId,
      url: InterfaceDictForm.url,
      orderCode: InterfaceDictForm.orderCode,
      dataType: InterfaceDictForm.dataType,
      sqlType: InterfaceDictForm.sqlType,
      settings: InterfaceDictForm.settings.join(','),
      remark: InterfaceDictForm.remark,
      sceneType: InterfaceDictForm.sceneType,
      orgId: isEmpty(InterfaceDictForm.orgId) ? store.userInfo.orgId : InterfaceDictForm.orgId
    };
    proxy.$http
      .post(url, InterfaceDict)
      .then((res: any) => {
        VxeMessage('保存成功', VxeNotifyType.success);
        clearForm();
        sltInterfaceDict.value.id = res.data.id;
        findInterfaceDictList();
      })
      .catch((err: any) => {
        VxeMessage('保存失败', VxeNotifyType.error);
      });
  });
}
function deleteBatchInterfaceDict() {
  const sltInterfaceDicts = (proxy.$refs.InterfaceDictTableRef as any).getCheckboxRecords();
  if (!(sltInterfaceDicts.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { ids: sltInterfaceDicts.map((p) => p.id) };
        const url = '/api/sys/deleteInterfaceDict';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            if (res.status.code === 200) {
              findInterfaceDictList(); // 获取检验仪器表格数据
              VxeMessage('删除成功', VxeNotifyType.success);
            } else {
              VxeMessage(res.status.msg, VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function clearForm() {
  InterfaceDictForm.id = null;
  InterfaceDictForm.code = '';
  InterfaceDictForm.name = '';
  InterfaceDictForm.type = [];
  InterfaceDictForm.interfaceGroup = [];
  InterfaceDictForm.ownSystem = [];

  InterfaceDictForm.typeName = '';
  InterfaceDictForm.interfaceGroupName = '';
  InterfaceDictForm.ownSystemName = '';

  InterfaceDictForm.url = '';
  InterfaceDictForm.explain = '';
  InterfaceDictForm.orderCode = '';
  InterfaceDictForm.orgId = '';
  InterfaceDictForm.remark = '';
  InterfaceDictForm.dataType = '';
  InterfaceDictForm.sqlType = 1;
  InterfaceDictForm.settings = [];
  InterfaceDictForm.sceneType = '';
  sltInterfaceDict.value = {};
}

function setInterfaceDictForm(row: any) {
  InterfaceDictForm.id = row.id;
  InterfaceDictForm.name = row.name;
  InterfaceDictForm.code = row.code;
  InterfaceDictForm.type = row.type ? row.type.split(',') : [];
  InterfaceDictForm.interfaceGroup = row.interfaceGroup ? row.interfaceGroup.split(',') : [];
  InterfaceDictForm.ownSystem = row.ownSystem ? row.ownSystem.split(',') : [];
  InterfaceDictForm.orderCode = row.orderCode;
  InterfaceDictForm.url = row.url;
  InterfaceDictForm.explain = row.explain;
  InterfaceDictForm.remark = row.remark;
  InterfaceDictForm.dataType = row.dataType;
  InterfaceDictForm.sqlType = row.sqlType;
  InterfaceDictForm.sceneType = row.sceneType;
  sltInterfaceDict.value = row;
}

function findParamFieldList() {
  fieldFormData.value = ref({});
  showGroupDialog.value = false;
  paramFieldList.length = 0;
  const url = '/api/sys/sysInterfaceDictField/findInterfaceDictFieldList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { pid: InterfaceDictForm.id, grade: 1 }
    })
    .then((res: any) => {
      paramFieldList.push(...res.data);
      if (paramFieldList.length > 0) {
        formItemCLick(paramFieldList[0], 0);
      }
      // if (paramFieldList[sltGroup.editFormItemIndex].compType == 'sltBusTable' || paramFieldList[sltGroup.editFormItemIndex].compType == 'checkBusTable') {
      //   getTableColumns();
      // }
    })
    .catch((err: any) => {
      // VxeMessage('获取获取当前字典的字段列表失败',VxeNotifyType.error)
    });
}
function addFormItem(compType) {
  try {
    const l = paramFieldList.length;
    const d = {
      pid: InterfaceDictForm.id,
      grade: 1,
      compType: '' /*控件类型*/,
      field: `field${l + 1}` /*字段名*/,
      title: `字段${l + 1}` /*标题*/,
      code: `${l + 1 <= 9 ? '0' + (l + 1) : l + 1}` /*属性编号*/,
      seq: l + 1 /*属性排序码*/,
      span: 24 /*栅格占据的列数（共 24 分栏）*/,
      align: 'left' /*内容对齐方式*/,
      titleAlign: 'right' /*标题对齐方式*/,
      titleWidth: '100px' /*宽度*/,
      titleColon: 0 /*是否显示标题冒号*/,
      titleAsterisk: 0 /*是否显示必填字段的红色星号*/,
      titleOverflow: 1 /*标题内容过长时显示为省略号*/,
      showTitle: 1 /*是否显示标题*/,
      vertical: 0 /*使用垂直布局*/,
      className: '' /*给表单项附加 className*/,
      contentClassName: '' /*给表单项内容附加 className*/,
      visible: 1 /*默认是否显示*/,
      visibleMethod: '' /*该方法的返回值用来决定该项是否显示*/,
      folding: '' /*默认收起*/,
      collapseNode: '' /*折叠节点*/,
      isCurrent: sltGroup.editFormItemIndex === l ? true : false /*当前编辑*/,
      fieldSource: '' /*属性数据来源*/,
      fieldOptions: [] /*属性取值集合*/,
      fieldDefValue: '' /*属性默认取值*/
    } as any;
    switch (compType) {
      case 'input':
        d.compType = 'input';
        break;
      case 'integer':
        d.compType = 'integer';
        break;
      case 'date':
        d.compType = 'date';
        break;
      case 'checkbox':
        d.compType = 'checkbox';
        break;
      case 'checkboxgroup':
        d.compType = 'checkboxgroup';
        d.fieldSource = '3';
        break;
      case 'radiogroup':
        d.compType = 'radiogroup';
        d.fieldSource = '3';
        break;
      case 'switch':
        d.compType = 'switch';
        break;
      case 'select':
        d.compType = 'select';
        d.fieldSource = '3';
        break;
      case 'textarea':
        d.compType = 'textarea';
        break;
      case 'color':
        d.compType = 'color';
        break;
      case 'sltBusTable':
        d.compType = 'sltBusTable';
        break;
      case 'checkBusTable':
        d.compType = 'checkBusTable';
        break;
      default:
        break;
    }
    paramFieldList.push(d);
  } catch (error) {
    console.log(error);
  }
}

function formItemCLick(item, index) {
  sltGroup.editFormItemIndex = index;
  fieldFormData.value = paramFieldList[index];
  showGroupDialog.value = true;
  // if (paramFieldList[sltGroup.editFormItemIndex].compType == 'sltBusTable' || paramFieldList[sltGroup.editFormItemIndex].compType == 'checkBusTable') {
  //   getTableColumns();
  // }
  paramFieldList.forEach((m, i) => {
    if (i === index) {
      m.isCurrent = true;
    } else {
      m.isCurrent = false;
    }
  });
}

function getChildren(obj: any) {
  const children = obj.children;

  if (!isEmpty(children)) {
    return getChildren(children[0]);
  } else {
    return obj;
  }
}
// 光标定位在指定字典分类上
function setCurTypeNode(nodeId: any) {
  proxy.$nextTick(() => {
    const treeName = 'dataTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(nodeId);
  });
}

interface RowVO {
  label: string;
  content: string;
}

async function insertEvent(row?: RowVO | number) {
  if (paramFieldList[sltGroup.editFormItemIndex].fieldOptions) {
    const record = {
      label: '',
      content: ''
    } as RowVO;
    paramFieldList[sltGroup.editFormItemIndex].fieldOptions.push(record);
  } else {
    paramFieldList[sltGroup.editFormItemIndex].fieldOptions = [];
    const record = {
      label: '',
      content: ''
    } as RowVO;
    paramFieldList[sltGroup.editFormItemIndex].fieldOptions.push(record);
  }
}
const xTableOptions = ref<VxeTableInstance<RowVO>>();

function removeSelectRowEvent() {
  const $table = xTableOptions.value;

  if ($table) {
    const index = paramFieldList[sltGroup.editFormItemIndex].fieldOptions.findIndex((item) => item == $table[0].getCurrentRecord());
    if (index > -1) {
      paramFieldList[sltGroup.editFormItemIndex].fieldOptions.splice(index, 1);
    }
  }
}
function deleteParamField(row: any) {
  proxy
    .$confirm('确定删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const index = paramFieldList.findIndex((item) => item == row);
      paramFieldList.splice(index, 1);
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function saveParamFieldList() {
  //if (paramFieldList.length > 0) {
  const url = '/api/sys/sysInterfaceDictField/saveSysParamFieldList';
  const obj: any = { id: InterfaceDictForm.id };
  obj.paramFieldList = paramFieldList;
  proxy.$http
    .post(url, obj)
    .then((res: any) => {
      VxeMessage('更新成功', VxeNotifyType.success);
      setTimeout(() => {
        //findCommonRemarkList();
      }, 500);
    })
    .catch((err: any) => {
      VxeMessage('更新失败', VxeNotifyType.success);
    });
  // } else {
  //   VxeMessage('无添加或修改数据', VxeNotifyType.error);
  // }
}
//重新排序
function sortAgain() {
  paramFieldList.sort((a, b) => Number(a.seq) - Number(b.seq));
  sltGroup.editFormItemIndex = paramFieldList.findIndex((f) => f.isCurrent);
}
function changeEvent(params) {
  //todo
}

// 改变设计模式的组件类型 3选1
function changeCorrection(item: any) {
  if (item == sysParamForm.classify) {
    sysParamForm.classify = '';
  } else {
    sysParamForm.classify = item;
  }
}
function changeIsLocal() {
  if (!sysParamForm.isLocal) {
    sysParamForm.isComputer = false;
  }
}

// 点击组件表格行
function SelectRowClick(row) {
  paramFieldList[sltGroup.editFormItemIndex].correTable = row.TABLE_NAME;
  getTableColumns();
}
// 清空组件输入框
function clearValueHandler() {
  paramFieldList[sltGroup.editFormItemIndex].correTable = '';
}
// 键盘事件删除输入框文字
function sliceHandler() {
  let newStr = paramFieldList[sltGroup.editFormItemIndex].correTable.slice(0, -1);
  paramFieldList[sltGroup.editFormItemIndex].correTable = newStr;
}
// 获取设计模式 选择字典
function getTableColumns() {
  correColumnList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictTable/getTableColumns';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { tableName: paramFieldList[sltGroup.editFormItemIndex].correTable } })
    .then((res: any) => {
      correColumnList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取获取设计模式选择字典失败',VxeNotifyType.error)
    });
}
function getTableDataList(row: any) {
  const columNameList = [];
  columNameList.push(row.correLabel);
  columNameList.push(row.correValue);

  tableDataList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictTableField/getTableFieldAndDataList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { tableName: row.correTable, columNameList: columNameList.join(',') } })
    .then((res: any) => {
      tableDataList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取可选的字典失败',VxeNotifyType.error)
    });
}
</script>

<style lang="scss" scoped>
#InterfaceDictDiv {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .splitpanes {
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }

      .right-Btn {
        margin: 0 0 0 5px;
        width: 40px;
      }

      // 右侧保存按钮
      .saveBtn {
        float: right;
        margin: 5px 10px;
      }

      .tableBody {
        height: calc(100% - 40px);
      }

      // 中间
      .tableBox {
        width: 100%;
        height: calc(100% - 40px);
      }

      .el-tabs {
        height: 100%;

        :deep(.el-tabs__content) {
          padding: 0;
          height: calc(100% - 39px);

          .el-tab-pane {
            height: 100%;

            .el-form {
              padding: 20px;
            }
          }
        }
      }

      // 各个组件与右侧删除按钮的间距
      .vxe-checkbox {
        margin: 5px;
      }

      .vxe-radio {
        margin: 5px;
      }

      .vxe-switch {
        margin: -3px;
      }
    }
  }
}
</style>
